﻿using System;
using System.IO;
using System.Net;

namespace GlobalStore.Core.StorageAccess
{
    public class FtpServerAccessor : IStorageAccessor
    {
        public FtpServerAccessor(AccessorDescriptor accessorDescriptor_)
        {
            _accessorDescriptor = accessorDescriptor_;
        }

        // TODO. Proper exception handling.
        public Stream CreateFilepartDownloadStream(Filepart filepart_)
        {
            Uri requestUri = CreateAbsoluteUri(filepart_);
            FtpWebRequest request = GetDownloadRequest(requestUri);
            FtpWebResponse response = GetDownloadResponse(request);
            Stream stream = response.GetResponseStream();
            return stream;
        }

        private FtpWebRequest GetDownloadRequest(Uri requestUri)
        {
            FtpWebRequest downloadRequest = (FtpWebRequest)FtpWebRequest.Create(requestUri);
            downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            downloadRequest.KeepAlive = true;
            downloadRequest.Credentials = CreateNetworkCredential();
            return downloadRequest;
        }

        private FtpWebResponse GetDownloadResponse(FtpWebRequest downloadRequest)
        {
            return (FtpWebResponse)downloadRequest.GetResponse();
        }

        private Uri CreateAbsoluteUri(Filepart filepart_)
        {
            return new Uri(_accessorDescriptor.ServerUri.AbsoluteUri + "/" + filepart_.RelativePath);
        }

        private NetworkCredential CreateNetworkCredential()
        {
            return new NetworkCredential(_accessorDescriptor.UserName, _accessorDescriptor.Password);
        }

        private AccessorDescriptor _accessorDescriptor;
    }
}
